<?php

namespace backend\controllers;

use backend\models\PackageEase;
use common\models\Country;
use Yii;
use backend\models\ProjectEase;
use backend\models\ProjectEaseSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\Tags;

/**
 * ProjectEaseController implements the CRUD actions for ProjectEase model.
 */
class ProjectEaseController extends Controller
{
    public $layout = 'yue-juan';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all ProjectEase models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (Yii::$app->request->post('hasEditable')) {
            $model = $this->findModel(Yii::$app->request->post('editableKey'));
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $posted = current($_POST['ProjectEase']);
            $post = ['ProjectEase' => $posted];
            if ($model->load($post)) {
                $editableAttribute = Yii::$app->request->post('editableAttribute');
                if ($model->save()) {
//                    $out = ['output' => $model->$editableAttribute, 'message' => ''];
                    if ($editableAttribute == 'category') {
                        $output = Yii::$app->params['project_category'][$model->category];
                    } elseif ($editableAttribute == 'level') {
                        $output = Yii::$app->params['project_ease_level'][$model->level];
                    } elseif ($editableAttribute == 'is_suit') {
                        $output = Yii::$app->params['is_suit'][$model->is_suit];
                    } elseif ($editableAttribute == 'source') {
                        $output = Yii::$app->params['project_ease_source'][$model->source];
                    } elseif ($editableAttribute == 'province') {
                        $arr_province = Country::localCity('`pid`=0 AND `order`>0');
                        $output = $arr_province[$model->$editableAttribute];
                    } elseif ($editableAttribute == 'creditor') {
                        $output = preg_replace('/中国|资产管理股份有限公司/', '', $model->creditor);
                    } else {
                        $output = $model->$editableAttribute;
                    }
                    $out = ['output' => $output, 'message' => ''];
                } else {
                    $out = ['output' => '', 'message' => serialize($model->getFirstErrors())];
                }
            } else {
                $out = ['output' => '', 'message' => 'not loaded'];
            }
            return $out;
        }

        $searchModel = new ProjectEaseSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        // 从 "response" 组件中获取 cookie 集合(yii\web\CookieCollection)
        $cookies = Yii::$app->response->cookies;
//        $cookies->getValue('project-ease-columns', '');
        $searchModel->columns = json_decode($_COOKIE['project-ease-columns']);
        if ($columns = Yii::$app->request->get("ProjectEaseSearch")) {
            $searchModel->columns = $columns['columns'];
            // 在要发送的响应中添加一个新的 cookie
//            $cookies->add(new \yii\web\Cookie([
//                'name' => 'project-ease-columns',
//                'value' => $columns['columns'],
//                'httpOnly' => false,
//                'expire' => 3600 * 24 * 30,
//            ]));
            setcookie('project-ease-columns', json_encode($columns['columns']), time() + 3600 * 24 * 30);
        }
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ProjectEase model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProjectEase model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ProjectEase();
        $tagModel = new Tags();
        if ($model->load(Yii::$app->request->post())) {
            $model->mortgage_type = $model->mortgage_type ? implode(',', $model->mortgage_type) : '';
            $model->owner = Yii::$app->user->id;
            $model->created_at = date('Y-m-d H:i:s');
            //自定义标签
            $tag_id = [];
            $arr_tags = explode('，', $model->tagTitle);
            unset($model->tagTitle);
            if (is_array($arr_tags) && count($arr_tags) > 0) {
                foreach ($arr_tags as $item) {
                    $cloneTagModel = clone $tagModel;
                    if ($item) {
                        if (Tags::find()->where(['title' => $item, 'user_id' => Yii::$app->user->id])->one() === null) {
                            $cloneTagModel->title = $item;
                            $cloneTagModel->user_id = Yii::$app->user->id;

                            $cloneTagModel->save();
                            $tag_id[] = $cloneTagModel->id;
                        } else {
                            Yii::$app->session->addFlash('warning', $item . '标签已存在');
                        }
                    }
                }
            }

            $model->tag = $model->tag ? array_merge($model->tag, $tag_id) : $tag_id;
            $model->tag = $model->tag ? implode(',', $model->tag) : '';

            if ($model->save()) {
                Yii::$app->session->setFlash('kv-detail-success', '创建成功');
                return $this->redirect(['index']);
            } else {
                Yii::$app->session->setFlash('kv-detail-warning', serialize($model->getFirstErrors()));
                if ($model->mortgage_type) {
                    $model->mortgage_type = explode(',', $model->mortgage_type);
                }
                return $this->redirect(Yii::$app->request->referrer);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ProjectEase model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $tagModel = new Tags();
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            $model->mortgage_type = $model->mortgage_type ? implode(',', $model->mortgage_type) : '';
            //自定义标签
            $tag_id = [];
            $arr_tags = explode('，', $model->tagTitle);

            unset($model->tagTitle);
            if (is_array($arr_tags) && count($arr_tags) > 0) {
                foreach ($arr_tags as $item) {
                    $cloneTagModel = clone $tagModel;
                    if ($item) {
                        if (Tags::find()->where(['title' => $item, 'user_id' => Yii::$app->user->id])->one() === null) {
                            $cloneTagModel->title = $item;
                            $cloneTagModel->user_id = Yii::$app->user->id;

                            $cloneTagModel->save();
                            $tag_id[] = $cloneTagModel->id;
                        } else {
                            Yii::$app->session->addFlash('warning', $item . '标签已存在');
                        }
                    }
                }
            }

            $model->tag = $model->tag ? array_merge($model->tag, $tag_id) : $tag_id;
            $model->tag = $model->tag ? implode(',', $model->tag) : '';
            $model->updated_at = date('Y-m-d H:i:s');
            if ($model->save()) {
                Yii::$app->session->setFlash('kv-detail-success', '编辑成功');
                return $this->redirect(['index']);
            } else {
                Yii::$app->session->setFlash('kv-detail-warning', serialize($model->getFirstErrors()));
                if ($model->mortgage_type) {
                    $model->mortgage_type = explode(',', $model->mortgage_type);
                }
                return $this->render('update', ['id' => $model->id, 'model' => $model]);
            }

        }

        if ($model->mortgage_type) {
            $model->mortgage_type = explode(',', $model->mortgage_type);
        }
        if ($model->tag) {
            $model->tag = explode(',', $model->tag);
        }
        return $this->render('update', [
            'model' => $model,
        ]);

    }

    /**
     * Deletes an existing ProjectEase model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ProjectEase model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return ProjectEase the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProjectEase::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     *
     */
    public function actionImport($package_id = 0)
    {
        if (empty($_FILES['project_file'])) {
            Yii::$app->session->setFlash('danger', '请先选择要上传的文件');
            return $this->redirect(Yii::$app->request->referrer); // terminate
        }
        $project_file = $_FILES['project_file'];
        $success = null;
        $filename = $project_file['name'];
        $ext = explode('.', basename($filename));
        $path = "uploads" . DIRECTORY_SEPARATOR . date('Ymd');
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $extension = array_pop($ext);
        if (!in_array($extension, ['xlsx', 'xls'])) {
//            Yii::$app->session->setFlash('danger', '请上传excel格式的文件');
//            return $this->redirect(Yii::$app->request->referrer); // terminate
            echo json_encode(['error' => '请上传excel格式的文件']);
            return;

        }
        $target = $path . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . $extension;
        if (move_uploaded_file($project_file['tmp_name'], $target)) {
            $this->processData($target, $package_id);
        } else {
            echo json_encode(['error' => '上传失败']);
            return;
//            Yii::$app->session->setFlash('danger', '上传失败');
        }
//        return $this->redirect(Yii::$app->request->referrer);
        return;
    }

    public function processData($filename, $package_id)
    {
        $projectEaseModel = new ProjectEase();
        $imported_data = \moonland\phpexcel\Excel::import(
            $filename,
            [
                'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
                'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
                'getOnlySheet' => 'Sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
            ]);

        //清单入库
        if (is_array($imported_data) && count($imported_data) > 0) {
            $project_fields = $projectEaseModel->attributeLabels();
            unset($project_fields['id'], $project_fields['code'], $project_fields['title'], $project_fields['mortgage_owner'], $project_fields['other_warrants_code'], $project_fields['mortgage_address'], $project_fields['mortgage_building_area'],
                $project_fields['mortgage_land_area'], $project_fields['created_at'], $project_fields['is_highlights'], $project_fields['management_status'], $project_fields['mortgage_type']);
            $success_count = 0;
            $failed_count = 0;
            $errors = [];
            $modelTag = new Tags();
            foreach ($imported_data as $key => $item) {
                //借款人为空则执行下一个循环
                if (empty($item[$projectEaseModel->getAttributeLabel('borrower')])) {
                    continue;
                }
                $projectEaseCloneModel = clone $projectEaseModel;
                foreach ($project_fields as $field_name => $label) {
                    switch ($field_name) {
                        case 'tag':
                            $tags = [];
                            $labels = explode('，', $item[$label]);
                            if (count($labels) > 0) {
                                foreach ($labels as $label_item) {
                                    if ($tag_id = Tags::find()->where("`title`='" . $label_item . "' AND (`user_id`=0 OR `user_id`=" . Yii::$app->user->id . ")")->one()->id) {
                                        $tags[] = $tag_id;
                                    } else {
                                        $modelTagClone = clone $modelTag;
                                        $modelTagClone->title = $label_item;
                                        $modelTagClone->user_id = Yii::$app->user->id;
                                        $modelTagClone->save();
                                        $tags[] = $modelTagClone->id;
                                    }
                                }
                                $projectEaseCloneModel->tag = implode(',', $tags);
                            }
                            break;
                        case 'level':
                            $project_ease_level = array_flip(Yii::$app->params['project_ease_level']);
                            $projectEaseCloneModel->level = $project_ease_level[$item[$label]];
                            break;
                        case 'source':
                            $project_ease_source = array_flip(Yii::$app->params['project_ease_source']);
                            $projectEaseCloneModel->source = $project_ease_source[$item[$label]];
                            break;
                        case 'package_id':
                            if ($package_id == 0) {// package_id got
                                $packageid = PackageEase::find()->where(['title' => trim($item[$label]), 'owner' => Yii::$app->user->id])->one()->id;
                                //隶属资产包未创建或不具备导入权限
                                if ($packageid == false) {
                                    $errors ['forbidden'][] = $item['借款人'];
                                    break 2;
                                }
                            }

                            //已导入的不再导入
                            if (ProjectEase::find()->where(['borrower' => $item['借款人'], 'package_id' => $package_id ? $package_id : $packageid])->one()) {
                                $errors ['exist'][] = $item['借款人'];
                                continue 3;
                            }
                            $projectEaseCloneModel->package_id = $package_id ? $package_id : $packageid;
                            break;
                        case 'province':
                            $province = Country::findOne(['title' => $item[$label]])->id;
                            $projectEaseCloneModel->province = $province ? $province : 0;
                            break;
                        case 'city':
                            $city = Country::find()->where("`title` = '" . $item[$label] . "' AND `pid` > 0")->one()->id;
                            $projectEaseCloneModel->city = $city ? $city : 0;
                            break;
                        case 'category':
                            $project_category = array_flip(Yii::$app->params['project_category']);
                            $category = $project_category[$item[$label]];
                            $projectEaseCloneModel->category = $category ? $category : 0;
                            break;
                        case 'is_suit':
                            $is_suit = array_flip(Yii::$app->params['is_suit']);
                            $projectEaseCloneModel->is_suit = $is_suit[$item[$label]];
                            break;
//                        case 'is_highlights':
//                            $is_highlights = array_flip(Yii::$app->params['is_highlights']);
//                            $projectEaseCloneModel->is_highlights = $is_highlights[$item[$label]];
//                            break;
//                        case 'management_status':
//                            $operation_status = array_flip(Yii::$app->params['operation_status']);
//                            $projectEaseCloneModel->management_status = $operation_status[$item[$label]];
//                            break;
//                        case 'mortgage_type':
//                            $mortgage_type = array_flip(Yii::$app->params['mortgage_type']);
//                            $arr_mortgage_type = explode('、', $item[$label]);
//                            $arr_type = [];
//                            if (is_array($arr_mortgage_type) && count($arr_mortgage_type) > 0) {
//                                foreach ($arr_mortgage_type as $type) {
//                                    $arr_type[] = $mortgage_type[$type];
//                                }
//                                $projectEaseCloneModel->mortgage_type = implode(',', $arr_type);
//                            }
//                            break;
                        default:
                            $projectEaseCloneModel->$field_name = $item[$label];
                    }
                }
                $projectEaseCloneModel->title = $projectEaseCloneModel->borrower;
                $projectEaseCloneModel->created_at = date('Y-m-d H:i:s');
                $projectEaseCloneModel->updated_at = date('Y-m-d H:i:s');
                $projectEaseCloneModel->owner = Yii::$app->user->id;
                if ($projectEaseCloneModel->package_id && $projectEaseCloneModel->save()) {
                    $success_count++;
                } else {
                    $failed_count++;
                    if (count($projectEaseCloneModel->getFirstErrors()) > 0) {
//                        Yii::$app->session->addFlash('danger', $item['借款人'] . '未导入' . serialize($projectEaseCloneModel->getFirstErrors()));
                        echo json_encode(['error' => $item['借款人'] . '未导入' . serialize($projectEaseCloneModel->getFirstErrors())]);
                        return;
                    }
                }
            }
//            Yii::$app->session->addFlash('success', '成功导入' . $success_count . '条。失败' . $failed_count . '条。');
            $msg = '';
            if (count($errors['forbidden']) > 0) {
                $msg .= '以下项目隶属资产包未创建或不具备导入权限：<hr>' . implode('、', $errors['forbidden']) . '<hr>';
            }
            if (count($errors['exist']) > 0) {
                $msg .= '以下项目已经导入过了：<hr>' . implode('、', $errors['exist']) . '<hr>';
            }
            if ($success_count == 0) {
                $msg2 = '请检查导入的文件格式是否符合模板要求。';
            }
            echo json_encode(['error' => $msg . '成功导入' . $success_count . '条。失败' . $failed_count . '条。' . $msg2]);
            return;
        } else {
            //表中无项目
//            Yii::$app->session->setFlash('danger', '表中无数据');
            echo json_encode(['error' => '表中无数据']);
            return;
        }
    }


    /**
     * @return $this
     */
    public function actionDownloadTemplate()
    {
        return Yii::$app->response->sendFile('project_import_template.xlsx');
    }
}
